<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\TransFormer;
use App\Models\Media;
use Illuminate\Http\Request;
use Storage;
use DB;

class UploadController extends Controller
{
    use TransFormer;

    protected $allowExt = array('jpg','png','jpeg');
    protected $mimeType = array('image/jpeg','image/png','image/jpg');
    protected $maxSize = 5300000;
    
    // 文件上传方法
    public function upload(Request $request)
    {
        $file = $request->file('file');
        $patient_id = $request->patient_id;

        $res = [];
        if ($file->isValid()) {
            // 扩展名
            $ext = $file->getClientOriginalExtension();
            if (!in_array($ext, $this->allowExt)) {
                $this->transFormerE(1002012, '上传文件后缀不允许');
            }
            // 上传文件大小
            $filesize=$file->getSize();
            if ($filesize > $this->maxSize) {
                $this->transFormerE(1002013, '上传文件超过限制大小');
            }
            // image/jpeg
            $mime_type = $file->getClientMimeType();
            if (!in_array($mime_type, $this->mimeType)) {
                $this->transFormerE(1002014, '上传文件类型不被允许');
            }
            // 临时文件的绝对路径
            $realPath = $file->getRealPath();

            $type = $request->type;
            if(!$type == 'card'){ // 身份证
                $type = 'egg';  // 心电图
            }
            // 设置文件上传目录 按照日期存储
            $file_relative_path = $type.'/'.date('Ymd');
            // 上传文件
            $filename = uniqid() . '.' . $ext;
            // public配置           
            $bool = Storage::disk('public')->put($file_relative_path.'/'.$filename, file_get_contents($realPath));
            $url = $file_relative_path.'/'.$filename;

            if($bool){  // 代表上传成功
                // 写入 表\
                $arr = [
                    'patient_id' => $patient_id,
                    'url' => $url,
                    'create_time' => date("Y-m-d H:i:s")
                ];
                $img_id = Media::insertGetId($arr);
                $res = [
                    'id' => $img_id,
                    'url' => $url,
                ];
            }else{
                $this->transFormerE(1002015, '上传失败，请重新上传');
            }
        }
        else {
            $this->transFormerE(1002016, '请上传正确的图片');
        }
        return $this->transFormer(200, '成功',$res);
    }

    public function delMedia(Request $request)
    {
        $id = (int)$request->id;
        if($id>0){
            Media::destroy($id);
        }else{
            $this->transFormerE(1002017, '删除失败');
        }
        return $this->transFormer(200, '成功');
    }
    
}
